package com.myboot.springbootmybatis.controller;

import com.myboot.springbootmybatis.pojo.Student;
import com.myboot.springbootmybatis.pojo.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class reidsController {

    /**
     * 1:在redis中存取数据
     * 2:在redis中获取数据
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/add")
    public String addStringRedis(String name,String value) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("xia", "zmj");
       return "向redis中存放数据";
    }
    @GetMapping("/select")
    public String selectRedis(String k){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object o = valueOperations.get(k);
        return "redis中key的名字====" + k +"value值是====="+ o;
    }
    @PostMapping("/restAdd/{k}/{v}")
    public String addRestfullRedis(
            @PathVariable String k,
            @PathVariable String v){
        stringRedisTemplate.opsForValue().set(k, v);
        return "stringRedisTemplate类型的redis存放数据";
    }
    @GetMapping("/restfulSelect/{k}")
    public String selectRestfullRedis(@PathVariable String k) {
        String s = stringRedisTemplate.opsForValue().get(k);
        return "k===" + k + "Value===" +s;
    }
    @PostMapping("/insert/{k}/{v}")
    public String selectRestfullRedis01(@PathVariable String k,@PathVariable String v) {
        //设置  redisTemplate  key和value的序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.opsForValue().set(k, v);
        return "";
    }

    /**
     * 使用json序列化
     *
     */
    @PostMapping("/JsonAdd")
    public String Json(){
        Teacher teacher = new Teacher();
        teacher.setId(1001);
        teacher.setName("zmj");
        teacher.setAge(23);
        //将key设置为String序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
        redisTemplate.opsForValue().set("Test",teacher);

        //反序列化
        Object test = redisTemplate.opsForValue().get("Test");
        return "kv中的value值序列化为JSON数组:K====" +test;
    }
}
